package com.playit.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javelingroup.navigate.dto.NavigateContext;
import com.javelingroup.navigate.dto.NavigateResult;
import com.javelingroup.navigate.service.NavigateService;


@WebServlet("/playit")
public class PlayIt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String breadCrumb = request.getParameter("breadCrumb");
		
		String navigation = removeLastField(breadCrumb); 
		
		// We need the following:
		// 1. The file that needs to be played - contained in the breadCrumb
		// 2. List of the rest of the files in the same folder - contained in the breadCrumb minus the last field (the file that needs to be played)
		
        ServletContext sc = getServletContext();

        NavigateContext navigateContext = new NavigateContext(navigation);
        NavigateService navigateService = new NavigateService();

        NavigateResult navigateResult = navigateService.createNavigation(navigateContext, sc);

        
        request.setAttribute("navigateResult", navigateResult);
        request.setAttribute("toPlay", breadCrumb);
        
        RequestDispatcher rd = request.getRequestDispatcher("/playIt.jsp");
        rd.forward(request, response);
		
	}

	private String removeLastField(String breadCrumb) {

		String toReturn = "";

		int lastLocation = breadCrumb.lastIndexOf(",");
		
		toReturn = breadCrumb.substring(0, lastLocation);
		
		return toReturn;
	}

}
